package com.ihelp.rest.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.ihelp.rest.base.po.SystemContext;

public class PageFilter implements Filter {
	
	private static String PAGE_SIZE_NAME = "ps";
	
	public void destroy() {

	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
//		if(request.getParameter("start") == null || request.getParameter("pageSize").equals("null")){
//			
//		}else
		SystemContext.setCurrentpage(getCurrentpage(request));
		SystemContext.setPagesize(getPageSize(request));
		try {
			chain.doFilter(arg0, arg1);
			SystemContext.setPagesize(10);
		} finally {
			SystemContext.removePagesize();
			SystemContext.removeCurrentpage();
			SystemContext.removePaging();
		}
	}

	public void init(FilterConfig arg0) throws ServletException {

	}
	
	public Integer getPageSize (HttpServletRequest request) {
		
		String psvalue = request.getParameter(PAGE_SIZE_NAME);
		if (psvalue != null && !psvalue.trim().equals("") &&!psvalue.trim().equals("undefined")) {
			Integer pageSize ;
			pageSize = Integer.parseInt(psvalue);
			request.getSession().setAttribute(PAGE_SIZE_NAME, pageSize);
		}
		
		Integer pagesize = SystemContext.getPagesize();
		return pagesize;
	}
	
	public Integer getCurrentpage (HttpServletRequest request) {
		String currentPageVal = request.getParameter("p");
		
		Integer page = 1;
		
		if (currentPageVal != null && !currentPageVal.trim().equals("")) {
			page = Integer.valueOf(currentPageVal);
		}
		
		return page;
	}
}
